import { bindable, containerless, bindingMode } from 'aurelia-framework';

@containerless
export class EmEditableDropdown {

    @bindable label = 'label';
    @bindable value = 'value';
    @bindable({ defaultBindingMode: bindingMode.twoWay }) selected;
    @bindable classes = "search selection";
    @bindable items;
    @bindable placeholder;
    @bindable onok;
    @bindable oncancel;

    editing = false;
    oldVal;

    selectedChanged(news, old) {
        if (news) {
            _.defer(() => {
                this.selectedItem = _.find(this.items, (item) => {
                    return item[this.value] == news;
                });
                // console.log('selectedChanged: ' + this.selectedItem);
            });
        }
    }

    /**
     * 当视图被附加到DOM中时被调用
     */
    attached() {

    }

    editHandler() {
        this.oldVal = this.selected;
        this.editing = true;
    }

    cancelHandler() {
        this.editing = false;
        this.selected = this.oldVal;
        this.oncancel && this.oncancel();
    }

    okHandler() {
        this.editing = false;
        this.onok && this.onok(this.selected);
    }
}
